import os
import time

from cpbox.tool import system
from cpbox.tool import utils
from cpbox.tool.concurrent import SimpleThreadPool

from cpapp.docker import Docker

RELEASE_APK_FILEPATH = 'app/build/outputs/apk/release/app-release.apk'

class Builder:

    def __init__(self, app, prj_root_dir, dry_run=True):
        self.app = app
        self.prj_root_dir = prj_root_dir
        self.options = {}
        self.options['concurrent_build'] = True
        self.dry_run = dry_run
        self.ensure_container()

    def process(self, build_request):
        build_task_list = build_request.generate_build_task_list(self)
        self.build_by_thread_pool(build_task_list)
        self.post_process_by_thread_pool(build_task_list)

    def post_process_by_thread_pool(self, build_task_list):
        artifact_list = []
        for build_task in build_task_list:
            artifact_list.extend(build_task.get_artifact_list())

        display_list = [item.to_dict()['apk'] for item in artifact_list]

        concurrent_amount = int(system.available_cpu_count())
        self.app.logger.info('concurrent amount: %s', concurrent_amount)
        pool = SimpleThreadPool(concurrent_amount)
        for artifact in artifact_list:
            pool.add_task(artifact.post_process)
        start = time.time()
        pool.start()
        pool.wait()
        self.app.logger.info('post_process_by_thread_pool, took: %ss', time.time() - start)

    def build_by_thread_pool(self, build_task_list):
        concurrent_amount = int(system.available_cpu_count() / 2)
        self.app.logger.info('concurrent amount: %s', concurrent_amount)
        pool = SimpleThreadPool(concurrent_amount)
        for build_task in build_task_list:
            pool.add_task(build_task.run)
        start = time.time()
        pool.start()
        pool.wait()
        self.app.logger.info('build_by_thread_pool, took: %ss', time.time() - start)

    def ensure_container(self):
        docker = Docker(self.app)
        return docker.ensure_container()
